package com.bears.god.sup.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.bears.god.sup.model.User;
import com.bears.god.sup.util.DBConnection;


public class UserDAOImp implements IUserDAO {
	private static final String FINDBYNAME= "select * from s_user where name=?";
	private static final String INSERT= "insert into s_user"
			+ "(email,name,password,user_dept) "
			+ "values(?,?,?,?)";
	
	
	@Override
	public User findByName(String name) throws Exception {
		PreparedStatement prep = null;
		Connection conn = null;
		User u = null;
		ResultSet  rst= null;
		
		try
		{
			//�������ݿ�
			conn = DBConnection.getConnection();
			prep = conn.prepareStatement(FINDBYNAME);
			prep.setString(1,name);
			rst = prep.executeQuery();
			if(rst.next())
			{
				u = new User();
				
				u.setEmail(rst.getString("email"));
				u.setName(rst.getString("name"));
				u.setPassword(rst.getString("password"));
				u.setUserDept(rst.getString("user_dept"));
			}
		}
		finally 
		{
			DBConnection.close(rst, prep, conn);
		}
		
		
		return u;
	}

	
	@Override
	public void save(User user) throws Exception {

		PreparedStatement prep = null;
		Connection conn =null;
		
		try {
			conn = DBConnection.getConnection();
			prep = conn.prepareStatement(INSERT,Statement.RETURN_GENERATED_KEYS);
			prep.setString(1, user.getEmail());
			prep.setString(2, user.getName());
			prep.setString(3, user.getPassword());
			prep.setString(4, user.getUserDept());
		
			prep.executeUpdate();
			ResultSet rst = prep.getGeneratedKeys();
			rst.next();
			int id = rst.getInt(1);
			user.setId(id);
			
		} finally {
			DBConnection.close(prep, conn);
			}
	}

	
	

}
